import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/bean/FileUpLoadBean.dart';
import 'package:flutter_ahj_app/base/bean/Result.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/utils/oss/ApiOssService.dart';
import 'package:flutter_ahj_app/base/utils/oss/StsBean.dart';

import 'oss/OSSUrlConsts.dart';

typedef void ClickCallback(String data);
typedef void FailedCallback(String errorMsg);

class HttpNoTokenUtils {
  static HttpNoTokenUtils instance;
  static String token;
  static Dio _dio;
  BaseOptions _options;
  static String isLogin = "0";
  static BuildContext context;
  static bool isLogInpage;
  static int inttime = 0;
  static bool isflag = true;

  static HttpNoTokenUtils _getHttpUtils() {
    isLogInpage = true;
    if (instance == null) {
      instance = new HttpNoTokenUtils();
    }
  }

  HttpNoTokenUtils() {
    // 初始化 Options
    _options = new BaseOptions(
        connectTimeout: 50000,
        receiveTimeout: 100000,
        headers: {
          "Authorization": "Basic eXVrb246eXVrb24",
        });

    _dio = new Dio(_options);
    _dio.interceptors
        .add(LogInterceptor(responseBody: true, requestBody: true)); //添加日志
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options,RequestInterceptorHandler requestInterceptorHandler) async {
      options.headers["Authorization"] =
          "Bearer " + UserInfoUtils.getUserToken();
      options.headers["User-Agent"] = Uri.encodeComponent( "app( " + UserInfoUtils.getPackageVeName()+");user("+UserInfoUtils.getUserId()+");"+UserInfoUtils.getDeVeName());
      return requestInterceptorHandler.next(options); //continue
    }, onResponse: (Response response,ResponseInterceptorHandler requestInterceptorHandler) {
      print(response.toString());

      // Do something with response data
      return requestInterceptorHandler.next(response); // continue
    }, onError: (DioError e,ErrorInterceptorHandler requestInterceptorHandler) {
      // Do something with response error
      return requestInterceptorHandler.next(e); //continue
    }));
  }

  static void setHttpUrl(String baseUrl) {
    _getHttpUtils();
    _dio.options.baseUrl = baseUrl;
  }

  ///获得 图片路径
  static httpGetImagePath(String httpUrl, Map map, ClickCallback callback,
      {Key key, FailedCallback failed, BuildContext context}) async {
    try {
      _getHttpUtils();
      _dio.options.baseUrl = httpUrl;
      HttpNoTokenUtils.context = context;
//      _show(context);
      var response = await _dio.get(httpUrl, queryParameters: map);
      Result result = Result.fromJson(json.decode(response.toString()));
      if (result.code == 0) {
        callback(response.toString());
      } else {}
    } catch (e) {
      print(e.toString());
//      _callBackFunction("121");
    }
  }

  static httpGet(String httpUrl, Map map, ClickCallback callback,
      {Key key, FailedCallback failed, BuildContext context}) async {
    try {
      _getHttpUtils();
      _dio.options.baseUrl = httpUrl;
      HttpNoTokenUtils.context = context;
      var response = await _dio.get(httpUrl, queryParameters: map);
      Result result = Result.fromJson(json.decode(response.toString()));

      if (result.code == 0) {
        callback(response.toString());
      } else {}
    } catch (e) {}
  }

  static List<FileData> fileLists = [];

  static httpUpLoadPost(
      String httpUrl, List<String> list, ClickCallback callback,
      {Key key,
      FailedCallback failed,
      BuildContext context,
      String fileUrlData}) async {
    try {
      bool isflage = true;
      HttpNoTokenUtils.context = context;

      if (fileUrlData == null) {
        fileUrlData = "";
      }
      File file = new File(list[0]);
      var data1 = {"a": "c"};
      HttpNoTokenUtils.httpGet(HttpBaseConst.serverUrl + OSSUrlConsts.URL_TOKEN, data1,
          (data) async {
        fileLists.clear();
        StsBean stsBean = StsBean.fromJson(json.decode(data));

        for (int i = 0; i < list.length; i++) {
          String fliePath = list[i];
          File file11 = new File(fliePath);
          if (file11.existsSync()) {
            String suffix = fliePath.substring(fliePath.lastIndexOf("."));
            int now = DateTime.now().millisecondsSinceEpoch;
            String alphabet =
                'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
            int strlenght = 5;
            String left = '';
            for (var i = 0; i < strlenght; i++) {
              left = left + alphabet[Random().nextInt(alphabet.length)];
            }
            String fileName = now.toString() + left + suffix;

            FileData fileData = FileData(
                fileName: fileName,
                urlPath: fileUrlData +
                    UserInfoUtils.getMID().toString() +
                    "/" +
                    fileName);
            fileLists.add(fileData);
            Response response = await ApiOssService.uploadImage(
                context,
                stsBean,
                fileUrlData +
                    UserInfoUtils.getMID().toString() +
                    "/" +
                    fileName,
                fliePath);
            if (response == null) {
              isflage = false;
            }
          }
        }
        FileUpLoadBean fileUpLoadBean = new FileUpLoadBean(
            code: isflage ? 0 : 1,
            msg: isflage ? "上传成功" : "上传失败",
            data: fileLists);
        callback(json.encode(fileUpLoadBean));
      });
    } catch (e) {}
  }
}
